package net.scdx.hotel.controller;

import net.scdx.hotel.dto.UserExecution;
import net.scdx.hotel.entity.Hotel;
import net.scdx.hotel.entity.Room;
import net.scdx.hotel.entity.User;
import net.scdx.hotel.service.HotelService;
import net.scdx.hotel.service.RoomService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import net.scdx.hotel.dto.OrderExecution;
import net.scdx.hotel.entity.Order;
import net.scdx.hotel.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.Integer.parseInt;


@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private HotelService hotelService;

    @Autowired
    private RoomService roomService;

    @RequestMapping("/list")
    public String orderPage(Model model, @RequestParam(value = "userId", required = false) Integer userId) {
        try{
            List<Order> orders = orderService.orderInfo(userId);
            model.addAttribute("orders", orders);
        }catch (Exception e) {
            e.printStackTrace();
        }

        return "order";
    }

    @GetMapping("/buy")
    public String  buyPage(int hotelId,int roomId, Model model){
        try {
            Hotel hotel = hotelService.queryHotel(hotelId);
            Room room= roomService.queryRoomByRoomId(roomId);
            if (hotel == null) {
                model.addAttribute("success", false);
                model.addAttribute("msg", "hotel found error");
            } else {
                model.addAttribute("success", true);
                model.addAttribute("hotel", hotel);
            }
            if(room==null){
                model.addAttribute("success", false);
                model.addAttribute("msg", "room not found");
            }
            else{
                model.addAttribute("success", true);
                model.addAttribute("room", room);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "buy";
    }

    @PostMapping("/submmit")
    public String  submmitOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try{
            Order order=new Order();

            String date1 = request.getParameter("checkin_time");
            String date2 = request.getParameter("checkout_time");
            Date now = new Date();
            order.setCreateTime(now);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date checkinTime = sdf.parse(date1);
            Date checkoutTime = sdf.parse(date2);
            order.setCheckinTime(checkinTime);
            order.setCheckoutTime(checkoutTime);

            //插入新的订单
            order.setPhone(request.getParameter("phone"));
            String totalPrice=request.getParameter("totalPrice");
            order.setTotalprice(Integer.parseInt(totalPrice));
            order.setStatus(2);  //状态 2是未支付
            order.setUserId(Integer.parseInt(request.getParameter("userId")));   //一开始写错
            int roomId=Integer.parseInt(request.getParameter("roomId"));
            order.setRoomId(roomId);

            request.setAttribute("order",order);
            request.setAttribute("roomCategory",request.getParameter("roomCategory"));


            UserExecution userExecution = orderService.addOrder(order);
            if (userExecution.isSuccess() == false) {
                request.setAttribute("submmitOrderFailure",true);
                request.setAttribute("msg",userExecution.getMsg());
            }

            //对应room表中的房间数减去amount   update
            int amount=Integer.parseInt( request.getParameter("amount")); //订购数
            int pcnt=Integer.parseInt( request.getParameter("pcnt"));  //房间总数
            int res=pcnt-amount;
            if(res<0){
                request.setAttribute("success", false);
                request.setAttribute("msg", "room amunt is not enough!");
            }
            boolean isOK=roomService.modifyRoomAmount(roomId,res);
            if(!isOK){
                request.setAttribute("success", false);
                request.setAttribute("msg", "update amount error");
            }

            if(res==0){
                boolean isUpdate=roomService.modifyIsempty(roomId);  //设置为0
                if(!isUpdate){
                    request.setAttribute("success", false);
                    request.setAttribute("msg", "update isEmpty error");
                }
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return "pay";
    }

    @GetMapping("/pay")  //付款成功后修改status状态
    public String  paySuccess(int orderId, HttpServletRequest request, HttpServletResponse response){
        //修改付款状态
        if(orderId<0){
            request.setAttribute("success", false);
            request.setAttribute("msg", "error");
        }

        try{
            boolean isOK=orderService.modifyOrderstatus(orderId);
            if(!isOK){
                request.setAttribute("success", false);
                request.setAttribute("msg", "error");
            }
           // request.getRequestDispatcher("/").forward(request, response);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return "paySuccess";
    }
}
